import 'package:flutter/material.dart';
import 'package:flutter_app/config.dart';
import 'package:flutter_app/widget/Utils.dart';
import 'package:flutter_app/widget/browser.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

class PostPage extends StatefulWidget {

  PostPage({Key key, List postList}) : super(key: key);

  final List postList = [];

  @override
  _PostPageState createState() {
    return new _PostPageState();
  }
}

class _PostPageState extends State<PostPage> {

  String title = "";
  String content = "";
  String postUrl = "${Config.apiHost}/post/page?";
  String searchUrl = "${Config.apiHost}/post/s/";

  int size = 16;
  int page = 1;

  List postList = [];

  ScrollController _scrollController = new ScrollController();

  void loadPagePost(String url, int page, int size) {
    http.get("${url}page=$page&size=$size").then((response) => {
      if(response.statusCode==200) {
        setState(() {
          postList = json.decode(response.body)['dataList'];
        })
      }
    });

  }

  void search(String url) {
    http.get(url)
        .then((response) =>
        setState(() {
          postList = json.decode(response.body);
        })
    );
  }

  @override
  void initState() {
    // 加载下一页数据
    _scrollController.addListener((){
      if(_scrollController.position.pixels == _scrollController.position.maxScrollExtent) {
        page++;
        Utils.showToast("正在加载第 $page 页...");
        Future.delayed(Duration(seconds: 2));
        http.get("${postUrl}page=$page&size=$size")
            .then((response) =>
            setState(() {
              postList.addAll(json.decode(response.body)['dataList']);
            })
        );
      }
    });
    // 初始化数据
    if(postList == null || postList.length <= 0) {
      loadPagePost(postUrl, page, size);
    }
    super.initState();
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
//      appBar: AppBar(
//        title: Row(
//          children: <Widget>[
//            Text("最新博客"),
//          ],
//        ),
//        actions: <Widget>[
//          IconButton(
//            icon: Icon(Icons.search),
//            onPressed: () {
//
//            },
//          ),
//        ],
//      ),
      floatingActionButtonLocation: FloatingActionButtonLocation.endFloat,
      floatingActionButton: FloatingActionButton.extended(
        onPressed: () {
          Navigator.of(context).pushNamed("search").then((value) {
            if (value != null) {
              Utils.showToast("搜索的关键词是：$value");
              search(searchUrl + value);
            } else {
              Utils.showToast("已取消搜索");
            }
          });
        },
        label: Text('Search'),
        icon: Icon(Icons.search),
        backgroundColor: Config.themeColor,
      ),
      body: RefreshIndicator(
        child: ListView(
          scrollDirection: Axis.vertical,
          children: _buildPostList(),
          controller: _scrollController,
        ),
        onRefresh: _handleRefresh,
      ),
    );
  }

  List<Widget> _buildPostList() {
    return postList.map((postMap) => _widgetItem(postMap)).toList();
  }

  Widget _widgetItem(Map postMap) {
    var id = postMap['id'];
    var title = postMap['postTitle'];
    var date = postMap['postDate'];
    DateTime dateTime = new DateTime.fromMillisecondsSinceEpoch(date);
    String dateStr = " ${dateTime.year}-${dateTime.month}-${dateTime.day} ${dateTime.hour}:${dateTime.minute}";
    var content = postMap['postContent'].replaceAll(" ", "").replaceAll("\n", "");
    return InkWell(
      child: Container(
        decoration: BoxDecoration(border: Border(bottom: BorderSide(color: Config.borderColor, width: 0.5))),
        padding: EdgeInsets.all(15),
        child: Column(
          children: <Widget>[
            Flex(
              direction: Axis.horizontal,
              children: <Widget>[
                Icon(Icons.map, color: Config.themeColor,),
                Expanded(
                    child: Text(
                      title,
                      style: TextStyle(fontSize: 16, fontWeight: FontWeight.w700),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    )
                ),
              ],
            ),
            Flex(
              direction: Axis.horizontal,
              children: <Widget>[
                Expanded(
                  child: Container(
                    padding: EdgeInsets.only(top: 5, bottom: 5),
                    child: Text(
                      content,
                      style: TextStyle(fontSize: 13, color: Config.titleColor),
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
                ),
              ],
            ),
            Flex(
              direction: Axis.horizontal,
              children: <Widget>[
                Icon(Icons.date_range, size: 12, color: Config.bodyColor),
                Expanded(
                  child: Text(
                    dateStr,
                    style: TextStyle(color: Config.bodyColor, fontSize: 12),
                    textAlign: TextAlign.start,
                  ),
                ),
                Icon(Icons.comment, size: 12, color: Config.bodyColor),
                Text(
                  " 0",
                  style: TextStyle(color: Config.bodyColor, fontSize: 12),
                  textAlign: TextAlign.end,
                ),
              ],
            ),

          ],
        ),
      ),
      onTap: () {
        Navigator.of(context).push(MaterialPageRoute(builder: (_) {
          return Browser(title: "博客详情", url: "http://blog.jvm123.com/app/post/$id/$title.html", shareUrl: "http://blog.jvm123.com/post/$id/$title.html",);
        }));
      },
      onLongPress: () => Utils.showToast("长按点击的内容为：$content"),
    );
  }

  Future<Null> _handleRefresh() async {
    Utils.showToast("正在加载...");
    page = 1;
    http.get("${postUrl}page=$page&size=$size")
        .then((response) =>
        setState(() {
          postList = json.decode(response.body)['dataList'];
        })
    );
    return null;
  }
}